import { Button, Card, DatePicker, Input, message, Select, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import * as XLSX from 'xlsx';
import enums from '../../../../public/enums';
import Ellipsis from '../../../components/Ellipsis';
import styles from './index.less';

const { Option } = Select;

@connect(() => ({}))
export default class index extends PureComponent {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  state = {
    vin: undefined,
    vehicleSeries: undefined,
    vehicleType: undefined,
    vhlType: undefined,
    enrollStatus: undefined,
    lockStatus: undefined,
    instructDate: undefined,
    vehicleSeriesList: [],
    vehicleTypeList: [],
    exportTaskVisible: false,
    riskEventList: [],
    riskEventId: undefined,
    riskTriggerDate: undefined,
    creditCompanyId: undefined,
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
    exportLoading: false,
    orgList: [],
    tboxRouseloading: false,
    tboxRouseCount: 15,
  };

  //查询车系
  handleGetVehicleSeriesList = () => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/msdevice/base/vehicle/series/list',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            vehicleSeriesList: response.data,
          });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  //根据车系code查询车型
  handleGetVehicleTypeList = seriesCode => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/msdevice/base/vehicle/type/list',
        seriesCode,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            vehicleTypeList: response.data || [],
          });
        } else {
          this.setState({
            vehicleTypeList: [],
          });
          message.error(response.statusMessage);
        }
      },
    });
  };

  componentDidMount() {
    this.handleGetVehicleSeriesList();
    //   this.handleGetriskEventList();
    this.handleTableData();
    //   this.handleGetOrgList();
  }

  handleTableData = () => {
    const {
      curPage,
      pageSize,
      vin,
      vehicleSeries,
      vehicleType,
      vhlType,
      enrollStatus,
      lockStatus,
      instructDate,
    } = this.state;
    this.setState({
      tableLoading: true,
    });
    let submitData = {
      vin,
      vehicleSeries,
      vehicleType,
      vhlType,
      enrollStatus,
      lockStatus,
    };
    if (instructDate) {
      submitData.fromDate = moment(instructDate[0]).format('YYYY-MM-DD ' + '00:00:00');
      submitData.endDate = moment(instructDate[1]).format('YYYY-MM-DD ' + '23:59:59');
    }
    this.props.dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url:
          '/reportmanagement/goodscarmonitorreport/page?curPage=' +
          curPage +
          '&pageSize=' +
          pageSize,
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.rows.length === 0 && response.data.pagination.current > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.total,
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleSearch = () => {
    this.handleTableData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        vin: undefined,
        vehicleSeries: undefined,
        vehicleType: undefined,
        vhlType: undefined,
        enrollStatus: undefined,
        lockStatus: undefined,
        instructDate: undefined,
      },
      () => {
        this.handleTableData();
      },
    );
  };

  //点击导出预警车辆
  handleExport = () => {
    const {
      vin,
      vehicleSeries,
      vehicleType,
      vhlType,
      enrollStatus,
      lockStatus,
      instructDate,
    } = this.state;
    this.setState({
      exportLoading: true,
    });
    let submitData = {
      vin,
      vehicleSeries,
      vehicleType,
      vhlType,
      enrollStatus,
      lockStatus,
    };
    if (instructDate) {
      submitData.fromDate = moment(instructDate[0]).format('YYYY-MM-DD ' + '00:00:00');
      submitData.endDate = moment(instructDate[1]).format('YYYY-MM-DD ' + '23:59:59');
    }
    this.props.dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/reportmanagement/goodscarmonitorreport/export',
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('导出成功,请稍等...', 3);
          this.handleCreateXlsx(response.data || []);
        } else {
          message.error(response.statusMessage);
          this.setState({
            exportLoading: false,
          });
        }
      },
    });
  };

  handleCreateXlsx = async dataList => {
    let newDataList = [];
    dataList.map(item => {
      const findVhlTyp = enums.vehicleType.array.find(e => e.value === item.vhlType);
      const findEnrollStatus = enums.enrollStatus.array.find(e => e.value === item.enrollStatus);
      const findLockStatuss = enums.lockStatus.array.find(e => e.value === item.lockStatus);
      const newItem = {
        vin: item.vin,
        vehicleSeries: item.vehicleSeries,
        vehicleType: item.vehicleType,
        vhlTypeDesc: findVhlTyp ? findVhlTyp.label : '',
        enrollStatusDesc: findEnrollStatus ? findEnrollStatus.label : '',
        dealerName: item.dealerName,
        lockStatusDesc: findLockStatuss ? findLockStatuss.label : '',
        commandTypeDesc: item.commandTypeDesc,
        commandSendTime: item.commandSendTime,
        lastLocationDesc: item.lastLocationDesc,
      };
      newDataList.push(newItem);
    });
    const header = [
      'vin',
      'vehicleSeries',
      'vehicleType',
      'vhlTypeDesc',
      'enrollStatusDesc',
      'dealerName',
      'lockStatusDesc',
      'commandTypeDesc',
      'commandSendTime',
      'lastLocationDesc',
    ];
    const headerDisplay = {
      vin: 'VIN',
      vehicleSeries: '车系',
      vehicleType: '车型',
      vhlTypeDesc: '车辆类型',
      enrollStatusDesc: '激活状态',
      dealerName: '所属经销商',
      lockStatusDesc: '锁车状态',
      commandTypeDesc: '指令类型',
      commandSendTime: '指令下发时间',
      lastLocationDesc: '车辆位置',
    };
    const newData = [headerDisplay, ...newDataList];
    const ws = XLSX.utils.json_to_sheet(newData, {
      header: header,
      skipHeader: true,
    });
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '商品车监控报表');
    XLSX.writeFile(wb, '商品车监控报表.xlsx');
    this.setState({
      exportLoading: false,
    });
  };

  render() {
    const {
      vin,
      vehicleSeries,
      vehicleType,
      vhlType,
      enrollStatus,
      lockStatus,
      instructDate,
      vehicleSeriesList,
      vehicleTypeList,
      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
      exportLoading,
    } = this.state;

    const {
      location: { pathname },
    } = this.props;

    const columns = [
      { title: 'VIN', dataIndex: 'vin' },
      {
        title: '车系',
        dataIndex: 'vehicleSeries',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车型',
        dataIndex: 'vehicleType',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车辆类型',
        dataIndex: 'vhlType',
        render: text => {
          let findText = enums.vehicleType.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '激活状态',
        dataIndex: 'enrollStatus',
        render: text => {
          let findText = enums.enrollStatus.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '所属经销商',
        dataIndex: 'dealerName',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '锁车状态',
        dataIndex: 'lockStatus',
        render: text => {
          let findText = enums.lockStatus.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '指令类型',
        dataIndex: 'commandTypeDesc',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      { title: '指令下发时间', dataIndex: 'commandSendTime' },
      {
        title: '车辆最后位置',
        dataIndex: 'lastLocationDesc',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
    ];

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'id',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };

    return (
      <div>
        <div className={styles.pateoSearch}>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>VIN号:</div>
            <Input
              placeholder="请输入vin号"
              value={vin}
              onChange={e => {
                this.setState({
                  vin: e.target.value,
                });
              }}
            />
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>车系:</div>
            <Select
              placeholder="请选择车系"
              value={vehicleSeries}
              onChange={e => {
                this.setState({
                  vehicleSeries: e,
                  vehicleTypeList: [],
                  vehicleType: undefined,
                });
                if (e) {
                  this.handleGetVehicleTypeList(e);
                }
              }}
            >
              {vehicleSeriesList.map(serie => {
                return (
                  <Option key={serie.seriesCode} value={serie.seriesCode}>
                    {serie.seriesName}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>车型:</div>
            <Select
              value={vehicleType}
              placeholder="请选择车型"
              onChange={e => {
                this.setState({
                  vehicleType: e,
                });
              }}
            >
              {vehicleTypeList.map(vehicleType => {
                return (
                  <Option key={vehicleType.typeCode} value={vehicleType.typeCode}>
                    {vehicleType.typeName}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>车辆类型:</div>
            <Select
              value={vhlType}
              placeholder="请选择车辆类型"
              onChange={e => {
                this.setState({
                  vhlType: e,
                });
              }}
            >
              {enums.vehicleType.array.map(e => {
                return (
                  <Option key={e.value} value={e.value}>
                    {e.label}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>激活状态:</div>
            <Select
              value={enrollStatus}
              placeholder="请选择激活状态"
              onChange={e => {
                this.setState({
                  enrollStatus: e,
                });
              }}
            >
              {enums.enrollStatus.array.map(e => {
                return (
                  <Option key={e.value} value={e.value}>
                    {e.label}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>锁车状态:</div>
            <Select
              value={lockStatus}
              placeholder="请选择锁车状态"
              onChange={e => {
                this.setState({
                  lockStatus: e,
                });
              }}
            >
              {enums.lockStatus.array.map(e => {
                return (
                  <Option key={e.value} value={e.value}>
                    {e.label}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>指令下发起止时间:</div>
            <DatePicker.RangePicker
              value={instructDate}
              onChange={e => {
                this.setState({
                  instructDate: e,
                });
              }}
            />
          </div>
          <div className={styles.searchBtn}>
            <Button
              onClick={() => this.handleSearch()}
              type={'primary'}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button onClick={() => this.handleReset()}>重置</Button>
          </div>
        </div>
        <div className={styles.pateoBtns}>
          {this.context.permissions.includes(pathname + '/goodsCarMonitorReport_export') ? (
            <div className={styles.btnItem}>
              <Button type="primary" loading={exportLoading} onClick={() => this.handleExport()}>
                导出报表
              </Button>
            </div>
          ) : null}
        </div>
        <Card bordered={false} style={{ marginTop: 10 }}>
          <Table {...tableProps} />
        </Card>
      </div>
    );
  }
}
